<template>
  <div>
    <!-- action:上传的地址
    show-file-list:是否显示已上传的文件列表
    on-success:上传成功以后做什么
    before-upload:上传之前做什么
    ------------------------------
    http-request:自定义上传逻辑,接收函数作为参数值,函数默认参数为上传的图片
     -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="uploadFn"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress
        v-if="showprogress"
        class="progress"
        type="circle"
        :percentage="percentage"
      />
    </el-upload>
  </div>
</template>

<script>
// 引入模块
var COS = require('cos-js-sdk-v5')
// 实例化cos对象
var cos = new COS({
  SecretId: 'AKIDRgf8PQCi03rPhkW1LPDk00jBNZYJo69w',
  SecretKey: 'XnnX0C9pENK2VifNq43mFSO5VdU4PWNy'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      showprogress: false,
      percentage: 0
    }
  },
  methods: {
    uploadFn(data) {
      // 在此处判断是否选择了文件
      if (data.file) {
        this.showprogress = true
        cos.putObject(
          {
            Bucket: 'tonglaoban-1308159406' /* 存储桶名称*/,
            Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
            Key: data.file.name /* 上传的图片名称 */,
            StorageClass: 'STANDARD',
            Body: data.file, // 上传文件对象
            onProgress: (progressData) => {
              this.percentage = parseInt(progressData.percent * 100)
            }
          },
          (err, data) => {
            if (err === null) {
              this.imageUrl = `https://${data.Location}`
            }
            this.showprogress = false
          }
        )
      }
    }
  }
}
</script>

<style  lang='scss' scoped>
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
